package cn.bjit.service.impl;

import cn.bjit.config.OSSconfig;
import cn.bjit.service.FileService;
import cn.bjit.util.CommonUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Autowired
    private OSSconfig  ossConfig;
    @Override
    public String uploadUserHeadImg(MultipartFile file) {
        //获取原文件名
        String originalFilename = file.getOriginalFilename();
        //获取相关配置
        String bucketName = ossConfig.getBucketname();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        //创建oss对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
          //>>构建文件名 user/2022/06/03/0f7f25c96b74d9191829aceafee5f75.jpg
          //获取当前时间2022-06-03T14:42:03.467 输出为2022/06/03
        LocalDateTime ldt = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String folder = dtf.format(ldt);//2022/06/03
        String fileName = CommonUtil.generateUUID();//90f7f25c96b74d9191829aceafee5f75
        String extension=originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName="user/"+folder+"/"+fileName+extension;

        try {
            PutObjectResult result = ossClient.putObject(bucketName, newFileName, file.getInputStream());
            //返回访问路径
            if (null != result) {
                //https://pass-user-service-img.oss-cn-beijing.aliyuncs.com/test/1.jpg
                String imgUrl = "https://"+bucketName+"."+endpoint+"/"+newFileName;
                return imgUrl;
            }
        } catch (IOException e) {
            log.error("上传头像失败:{}",e);
        }
        return null;
    }
}
